<?php

/**
 * 获取用户详细信息
 * @param type $code    I('get.code')
 * @return array
 */
function checkUser($code) {
    vendor('Mpwexin');
    $mp_weixin = new \Mpwexin();
    $web = M("web")->where('id=' . session('webid'))->find();
    //需要设置时间限制 过期后重新请求，未过期直接取session
    //获取用户access_token param:corpid,应用secret
    $access_token = $mp_weixin->getToken($web['wx_corpid'], $web['wx_appsecret']);
    session('access_token', $access_token);
    //根据code获取openid
    if ($code) {
        $res = $mp_weixin->getAccessTokenByCode($access_token, $code);
        $result['openid'] = $res['UserId'] ? $res['UserId'] : $res['OpenId'];

        //根据access_token获取用户详细信息
        $ticket = $mp_weixin->getTicket($access_token, $res['user_ticket']);
        $result['userid'] = $ticket['userid'];  //成员UserID 
        $result['name'] = $ticket['name'];  // 	成员姓名 
        $result['department'][0] = $ticket['department'];  // 	成员所属部门 
        $result['position'] = $ticket['position'];  //职位信息 
        $result['mobile'] = $ticket['mobile'];  // 	成员手机号，仅在用户同意snsapi_privateinfo授权时返回 
        $result['gender'] = $ticket['gender'];  //性别。0表示未定义，1表示男性，2表示女性 
        $result['email'] = $ticket['email'];    // 	成员邮箱，仅在用户同意snsapi_privateinfo授权时返回 
        $result['avatar'] = $ticket['avatar'];  //头像url。注：如果要获取小图将url最后的”/0”改成”/64”即可 
        return $result;
    }

    return false;
}

function getToken() {
    vendor('Mpwexin');
    $mp_weixin = new \Mpwexin();
    $web = M("web")->find(1);
    //需要设置时间限制 过期后重新请求，未过期直接取session
    //获取用户token
    $token = $mp_weixin->getToken($web['wx_appid'], $web['wx_appsecret']);
    session('token', $token);

    return $token;
}

//获取微信用户id
function getWxUserid($user_id) {
    return M('user')->where('user_id="' . $user_id . '"')->getField('openid');
}

function getProductPrice($id) {
    $map['id'] = $id;
    return M("product")->where($map)->getField("price");
}

//获取用户的openid
function getBaseInfo($appid, $url) {
    //1.获取到code
    $redirect_uri = urlencode($url); //这里的地址需要http://
    $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $appid . "&redirect_uri=" . $redirect_uri . "&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
    header('location:' . $url);
}

//获取中文用户名
function getChineseName($user_id) {
    return M('user')->where('user_id="' . $user_id . '"')->getField('user_name');
}

/*
 * 企业微信发送提醒接口
 * param $users     array[string]   用户id
 * param $content   string          提醒内容
 */

function setWeixinMsg($users, $content, $webid = '') {
    if ($webid == '') {
        $webid = session('webid');
    }
    vendor('Mpwexin');
    $mp_weixin = new \Mpwexin();
    $web = M('web')->where('id=' . $webid)->find();
    if (is_array($users)) {
        $toUser = '';
        foreach ($users as $key => $user) {
            $tempUser = getWxUserid($user);
            $toUser .= $tempUser . '|';
        }
        $toUser = rtrim($toUser, '|');
    } else {
        $toUser = getWxUserid($users);
    }
    $mp_weixin->setMessage($web['wx_corpid'], $web['wx_appsecret'], $toUser, $content, $web['wx_agentid']);
}

/*
 * 获取部门中的用户
 * params string    $ids   部门id
 * return array
 */

function getDeptUsers($ids) {
    if ($ids == 'ALL_DEPT') {
        //所有部门
        $ids = M('department')->getField('dept_id', true);
    } else {
        $ids = explode(',', $ids);
        if (!is_array($ids)) {
            $ids[] = $ids;
        }
    }
    $map['dept_id'] = array('in', $ids);
    return M('user')->where($map)->getField('user_id', true);
}

/*
 * 获取符合角色的用户
 * params string    $ids   角色id
 * return array
 */

function getPrivUsers($ids) {
    $ids = explode(',', substr($ids, 0, -1));
    if (!is_array($ids)) {
        $ids[] = $ids;
    }
    $map['user_priv'] = array('in', $ids);
    return M('user')->where($map)->getField('user_id', true);
}

/*
 * 添加步驟名和是否指定主办人到符合条件的數組中, 如果top_default = 2,无主办人会签，nextStep页面不显示主办人行
 * param $data  符合条件的数组 $this->getData(,,,)
 * param $flow_id   流程ID
 * param $prcs_id   步骤Id
 */

function addPrcsname($data, $flow_id, $prcs_id) {
    foreach ($data as $key => $row) {
        $data[$key]['top_default'] = M('flow_process')->where(array('flow_id' => $flow_id, 'prcs_id' => $prcs_id))->getField('top_default');
        $data[$key]['prcs_name'] = M('flow_process')->where(array('flow_id' => $flow_id, 'prcs_id' => $prcs_id))->getField('prcs_name');
//        if (strstr($data[$key]['prcs_name'], '会签')) {
//            $data[$key]['flag'] = 1;
//        } else {
//            $data[$key]['flag'] = 0;
//        }
    }
    return $data;
}

/*
 * 获取步骤名称
 * param $run_id    流程进程id
 * param $flow_id   流程ID
 * param $user_id   用户Id
 * return string    
 */

function getStepName($flow_id, $prcs_id) {
    $sMap['flow_id'] = $flow_id;
    $sMap['prcs_id'] = $prcs_id;

    return M('flow_process')->where($sMap)->getField('prcs_name');
}

function getFlagname($flag) {
    switch ($flag) {
        case 0:
            $str = '已退回';
            break;
        case 1:
            $str = '未接收';
            break;
        case 2:
            $str = '办理中';
            break;
        case 3:
            $str = '已转交';
            break;
        case 4:
            $str = '已办结';
            break;
    }
    return $str;
}

/* 计算时间差
 * param  int  时间戮
 * returm array  [天，时，分，秒]
 */

function timediff($begin_time, $end_time) {
    if ($begin_time < $end_time) {
        $starttime = $begin_time;
        $endtime = $end_time;
    } else {
        $starttime = $end_time;
        $endtime = $begin_time;
    }

    //计算天数
    $timediff = $endtime - $starttime;
    $days = intval($timediff / 86400);
    //计算小时数
    $remain = $timediff % 86400;
    $hours = intval($remain / 3600);
    //计算分钟数
    $remain = $remain % 3600;
    $mins = intval($remain / 60);
    //计算秒数
    $secs = $remain % 60;
    $res = array("day" => $days, "hour" => $hours, "min" => $mins, "sec" => $secs);
    return $res;
}

function get_form($form_id, $run_id) {
    //----- 取表单数据 --------
    $datas = M('flow_run_data')->where('run_id=' . $run_id)->order('item_id')->select();
    foreach ($datas as $key => $row) {
        $items[$row['item_id']] = $row['item_data'];
    }
    $print_model = M('flow_form_type')->where('form_id=' . $form_id)->getField('print_model_short');
    //print_r($form_id);
    //-------- Html 智能分析 -----------
    include("/Public/form/" . $form_id . ".php");
    // print_r($ELEMENT_ARRAY);die;
    if (!empty($ELEMENT_ARRAY)) {
        foreach ($ELEMENT_ARRAY as $ENAME => $ELEMENT_ARR) {
            $ETAG = $ELEMENT_ARR["TAG"];
            $ELEMENT = $ELEMENT_ARR["CONTENT"];
            $EVALUE = $ELEMENT_ARR["VALUE"];
            $ETITLE = $ELEMENT_ARR["TITLE"];
            $ECLASS = $ELEMENT_ARR["CLASS"];
            $ITEM_ID = $ELEMENT_ARR["ITEM_ID"];
            if ($ECLASS != "DATE" && $ECLASS != "USER") {
                $FORM_DATA[$ETITLE] = [$items[$ITEM_ID], $ITEM_ID];
                if ($FORM_DATA[$ETITLE] == "NAAAALOaxuKqfjdcOLp66SG1uokBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==")
                    $FORM_DATA[$ETITLE] = "";
                //echo $ETITLE."-".$FORM_DATA[$ETITLE]."<br>";
            }
        }
    }
    return $FORM_DATA;
}
function getFormCondition($desc, $form_data, $flow_prcs, $prcs_in_set, $htmlArr) {
    $lists = explode('<br>', $desc);
    $str = '';
    $i = 0;
    foreach ($lists as $k => $v) {
        if ($v) {
            $in = stripos($v, 'include');
            if ($in) {
                $v = str_replace('include ', ' like \'%', $v);
                $v = rtrim(trim($v), "'") . "%'";
            }

            $ex = stripos($v, 'exclude');
            if ($ex) {

                $v = str_replace('exclude ', ' not like \'%', $v);
                $v = rtrim(trim($v), "'") . "%'";
            }
            $tmp = explode(" ", trim($v));
            if (stripos($v, 'not like')) {
                $key = $tmp[0];
                $flag = $tmp[2] . ' ' . $tmp[3];
                $value = $tmp[4];
            } elseif (stripos($v, 'like')) {
                $key = $tmp[0];
                $flag = $tmp[2];
                $value = $tmp[3];
            } else {
                $key = $tmp[0];
                $flag = $tmp[1];
                $value = $tmp[2];
            }

            foreach ($htmlArr as $k_h => $v_h) {
                if ($key == $v_h) {
                    $key = $k_h;
                }
            }
            $sql[] = $key . ' ' . $flag . ' "' . $value . '"';
        }
    }
    //print_r($sql);echo $prcs_in_set;
    foreach ($sql as $k2 => $v2) {
        $prcs_in_set = str_replace('[' . ($k2 + 1) . ']', $v2, $prcs_in_set);
    }

    //echo $prcs_in_set;die;
    return $prcs_in_set;
}
function check_condition($form_data, $condition, $condition_set, $run_id, $prcs_id, $flow_prcs, $condition_desc) {
    if ($condition == "")
        return "";
    $condition_set_value = $condition_set;
    $condition_set_desc = $condition_set;
    $condition_set_desc = str_replace("and", "并且", $condition_set_desc);
    $condition_set_desc = str_replace("or", "或者", $condition_set_desc);
    $condition_set_desc = str_replace("!", "非", $condition_set_desc);
    $con_array = explode("\n", $condition);
    foreach ($con_array as $k => $v) {
        if ($v) {
            $tmp = trim(str_replace(" ", "", $v));
            if ($tmp == '') {
                continue;
            }
            $rule_array = explode("'", $v);
            $item_title = $rule_array[1];
            $item_con = $rule_array[2];
            $item_value = $rule_array[3];
            if (strstr($item_title, "[主办人会签意见]") || strstr($item_title, "[从办人会签意见]")) {
                //$prcs = M('flow_run_prcs')->where(array('run_id'=>$run_id,'prcs_id'=>$prcs_id))->select();
                $query = "select user_id,prcs_id from flow_run_prcs where run_id=$run_id and prcs_id=$prcs_id";
                if (strstr($item_title, "[主办人会签意见]"))
                    $query .= " and op_flag=1";
                else
                    $query .= " and op_flag=0";
                $datas = M()->query($query);
                $feed_content = "";
                $prcs_user = "";
                foreach ($datas as $key => $row) {
                    $prcs_user = $row["user_id"];
                    $feed_content .= M('flow_run_feedback')->where("run_id=$run_id and prcs_id=$prcs_id and user_id='$prcs_user'")->getField('content');
                }

                if ($prcs_user != "")
                    $form_data[$item_title] = $feed_content;
                else
                    $form_data[$item_title] = "无-从-办-人";
            }
            elseif (strstr($item_title, "[公共附件名称]")) {
                $attachment_name = M('flow_run')->where('run_id=' . $run_id)->getField('attachment_name');
                $form_data[$item_title] = $attachment_name;
                
            }
 
            elseif (strstr($item_title, "[当前步骤号]"))
                $form_data[$item_title] = $prcs_id;
            elseif (strstr($item_title, "[当前流程设计步骤号]"))
                $form_data[$item_title] = $flow_prcs;
            elseif (strstr($item_title, "[当前主办人姓名]"))
                $form_data[$item_title] = getChineseName(session('user_id'));
            elseif (strstr($item_title, "[当前主办人角色]")) {
                $priv_name = M('user_priv')->where('user_priv=' . session('user_priv'))->getField('priv_name');
                $form_data[$item_title] = $priv_name;
               

            } else if (strstr($item_title, "[当前主办人辅助角色]")) {
                $query1 = "select priv_name from user_priv where FIND_IN_SET(user_priv,'" . session('user_priv_other') . "')";
                $data1 = M()->query($query1);
                foreach ($data1 as $key1 => $row1) {
                    $priv_name .= $row1['priv_name'] . ",";
                }

                $form_data[$item_title] = $priv_name;
            } elseif (strstr($item_title, "[当前主办人部门]"))
                $form_data[$item_title] = session('dept_id');

            $check_pass = 0;
            if (stristr($item_con, "include")) {
                $item_con_desc = "包含";
                if (stristr($form_data[$item_title], $item_value))
                    $check_pass = 1;
            }
            elseif (stristr($item_con, "exclude")) {
                $item_con_desc = "不包含";
                if (!stristr($form_data[$item_title], $item_value))
                    $check_pass = 1;
            }
            //类型判断条件
            elseif (stristr($item_con, "==") || stristr($item_con, "!==")) {
                if (stristr($item_con, "=="))
                    $flag = true;
                else
                    $flag = false;
                $item_con_desc = $flag ? "类型为" : "类型不能为";
                if ($item_value == "数值" && $flag == is_numeric($form_data[$item_title]))
                    $check_pass = 1;
                elseif ($item_value == "日期" && $flag == is_date($form_data[$item_title]))
                    $check_pass = 1;
                elseif ($item_value == "日期+时间" && $flag == is_date_time($form_data[$item_title]))
                    $check_pass = 1;
            }
            elseif (stristr($item_con, ">=")) {
                // 新增字段和字段的比较（#为标识符） By ZLL
                if (strpos($item_value, "#") > 0)
                    $item_value = $form_data[str_replace("#", "", $item_value)];
                $item_con_desc = "大于等于";
                if ($form_data[$item_title] >= $item_value)
                    $check_pass = 1;
                if (is_date_time($form_data[$item_title]) || is_date($form_data[$item_title])) {
                    if (strtotime($form_data[$item_title]) >= strtotime($item_value))
                        $check_pass = 1;
                }
            }
            elseif (stristr($item_con, "<=")) { // 新增字段和字段的比较（#为标识符） By ZLL
                if (strpos($item_value, "#") > 0)
                    $item_value = $form_data[str_replace("#", "", $item_value)];
                $item_con_desc = "小于等于";
                if ($form_data[$item_title] <= $item_value)
                    $check_pass = 1;
            }
            elseif (stristr($item_con, "<>")) {
                echo strpos($item_value, "#");
                // 新增字段和字段的比较（#为标识符） By ZLL
                if (strpos($item_value, "#") > 0)
                    $item_value = $form_data[str_replace("#", "", $item_value)];
                $item_con_desc = "不等于";
                if ($form_data[$item_title] != $item_value)
                    $check_pass = 1;
            }
            elseif (stristr($item_con, ">")) { // 新增字段和字段的比较（#为标识符） By ZLL
                if (strpos($item_value, "#") > 0)
                    $item_value = $form_data[str_replace("#", "", $item_value)];
                $item_con_desc = "大于";
                if ($form_data[$item_title] > $item_value)
                    $check_pass = 1;
            }
            elseif (stristr($item_con, "<")) { // 新增字段和字段的比较（#为标识符） By ZLL
                if (strpos($item_value, "#") > 0)
                    $item_value = $form_data[str_replace("#", "", $item_value)];
                $item_con_desc = "小于";
                if ($form_data[$item_title] < $item_value)
                    $check_pass = 1;
            }
            elseif ($item_con == "=") { // 新增字段和字段的比较（#为标识符） By ZLL
                if (strpos($item_value, "#") > 0)
                    $item_value = $form_data[str_replace("#", "", $item_value)];
                $item_con_desc = "等于";
                if ($form_data[$item_title] == $item_value)
                    $check_pass = 1;
            } else
                $item_con = "";
            //单个条件描述
            if ($item_value == "")
                $item_value = "空";
            $set_desc = "$item_title $item_con_desc $item_value";
            //单个条件判断
            if (!$check_pass && (count($con_array) - 1 == 1)) {//条件$I为假
                if ($item_con == "" || $item_title == "") {
                    $not_pass = "条件表达式错误：\n" . $v . "\n";
                    return $not_pass;
                } else {
                    if ($condition_set == "") {
                        $not_pass = "不符合条件：\n" . $set_desc . "\n";
                        return $not_pass;
                    }
                    $set_value = "0";
                }
            } else//条件$I为真
                $set_value = "1";
            //形成条件公式值运算和条件公式描述
            $count = $key + 1;
            $condition_set_value = str_replace("[$count]", $set_value, $condition_set_value);
            $condition_set_desc = str_replace("[$count]", "[$set_desc]", $condition_set_desc);
        }
    }
    if ($condition_set != "") {
        //条件公式值运算判断
        eval("\$result=($condition_set_value);");
        if (!$result)
            $not_pass = "不符合条件公式：" . $condition_set_desc;
        else
            $not_pass = "SETOK" . $condition_set_desc;
    }
}

function is_date_time($date_time_str) {
    if ($date_time_str == null || strlen($date_time_str) == 0)
        return false;
    $date_time_arry = explode(" ", $date_time_str);
    if (is_date($date_time_arry[0]) && is_time($date_time_arry[1]))
        return true;
    return false;
}

function is_date($str) {
    $year = "";
    $month = "";
    $day = "";

    $len = strlen($str);

    $offset = 0;
    $i = strpos($str, "-", $offset);
    $year = substr($str, $offset, $i - $offset);

    $offset = $i + 1;
    if ($offset > $len)
        return false;

    if ($i) {
        $i = strpos($str, "-", $offset);
        $month = substr($str, $offset, $i - $offset);
        $offset = $i + 1;

        if ($offset > $len)
            return false;

        if ($i)
            $day = substr($str, $offset, $len - $offset);
    }

    if ($year == "" || $month == "" || $day == "")
        return false;

    if (!checkdate(intval($month), intval($day), intval($year)))
        return false;

    return true;
}

//获取工作计划类别
function getPlanType($type) {
    if ($type == 0) {
        return '无';
    } else {
        return M('plan_type')->where('type_id=' . $type)->getField('type_name');
    }
}

//获取工作计划模式
function getPlanMode($type) {
    return M('plan_type')->where('type_id=' . $type)->getField('mode');
}

/*
 * 获取多个用户姓名
 * paran $names 用户id
 * return string
 */

function getMoreUsername($names) {
    $str = '';
    $names = rtrim($names, ',');
    if (stripos($names, ',') == false) {
        $str = getChineseName($names);  //单个用户
    } else {
        $names = explode(',', $names);
        foreach ($names as $k1 => $r1) {
            $str .= getChineseName($r1) . ', ';
        }
        $str = rtrim($str, ',');
    }
    return $str;
}

/*
 * 获取多个部门
 * paran $ids 部门id
 * return string
 */

function getMoreDeptname($ids) {
    $str = '';
    $ids = rtrim($ids, ',');
    if ($ids != 'ALL_DEPT') {
        if (stripos($ids, ',') == FALSE) {  //单个部门
            $str = getDeptName($ids);
        } else {
            $ids = explode(',', $ids);
            foreach ($ids as $k1 => $r1) {
                $str .= M('department')->where('dept_id=' . $r1)->getField('dept_name') . ',';
            }
            $str = rtrim($str, ',');
        }
    } else {
        $str = '全体部门';
    }
    return $str;
}

/*
 * 获取多个角色
 * paran $ids 角色id
 * return string
 */

function getMorePrivname($ids) {
    $str = '';
    $ids = rtrim($ids, ',');
    if (stripos($ids, ',') == false) {
        $str = getPrivName($ids);  //单个角色
    } else {
        $ids = explode(',', $ids);
        foreach ($ids as $k1 => $r1) {
            $str .= getPrivName($r1) . ', ';
        }
        $str = rtrim($str, ',');
    }
    return $str;
}

/*
 * 获取条件中部门和角色对应的id值 
 * params $field    条件中的键
 * params $arr      条件中的值
 * update by qiaoshoujuan 2017-09-14 
 */

function getDartPrivId($field, $arr) {
    $params = array();
    foreach ($field as $key => $row) {
        $tempkey = array_values($row);

        switch ($tempkey[0]) {
            case 'CUR_USER_DEPT':   //当前主办人部门
                $map['dept_name'] = array('like', '%' . trim($arr[$key]) . '%');
                $data[$key] = M('department')->where($map)->getField('dept_id');
                break;
            default:    //主办人角色（cur_user_priv）、主办人辅助角色（cur_user_priv_other）、流程发起人角色（FLOW_USER_PRIV）
                $map['priv_name'] = array('like', '%' . rtrim($arr[$key]) . '%');
                $ids = M('user_priv')->where($map)->getField('user_priv', true);
                $data[$key] = implode($ids, ',');
        }
    }

    return $data;
}

/*
 * 获取当月第一天和最后一天
 * param $data  当前时间 date('Y-m-d H:i:s')
 * return $array
 */

function getthemonth($date) {
    $firstday = date('Y-m-01', strtotime($date));
    $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
    return array($firstday, $lastday);
}

function getChineseWeek($week) {
    switch ($week) {
        case 0:
            $str = '星期日';
            break;
        case 1:
            $str = '星期一';
            break;
        case 2:
            $str = '星期二';
            break;
        case 3:
            $str = '星期三';
            break;
        case 4:
            $str = '星期四';
            break;
        case 5:
            $str = '星期五';
            break;
        default:
            $str = '星期六';
    }
    return $str;
}

function getDeptName($dept_id) {
    if ($dept_id == 'ALL_DEPT' || $dept_id == 0) {
        return '全体部门';
    } else {
        return M('department')->where('dept_id=' . $dept_id)->getField('dept_name');
    }
}

/**
 * 返回要截取的字符串
 * $str:要截取的字符串
 * $start=0：开始位置，默认从0开始
 * $length：截取长度
 * $charset=”utf-8″：字符编码，默认UTF－8
 * $suffix=true：是否在截取后的字符后面显示省略号，默认true显示，false为不显示
 * Author 张颖衡 
 */
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true) {
    if (function_exists("mb_substr")) {
        if ($suffix)
            return mb_substr($str, $start, $length, $charset) . "...";
        else
            return mb_substr($str, $start, $length, $charset);
    }
    elseif (function_exists('iconv_substr')) {
        if ($suffix)
            return iconv_substr($str, $start, $length, $charset) . "...";
        else
            return iconv_substr($str, $start, $length, $charset);
    }
    $re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef]
              [x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
    $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
    $re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
    $re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
    preg_match_all($re[$charset], $str, $match);
    $slice = join("", array_slice($match[0], $start, $length));
    if ($suffix)
        return $slice . "…";
    return $slice;
}

function getPrivName($id) {
    return M('user_priv')->where('user_priv=' . $id)->getField('priv_name');
}

//获取公告类型
function getNoticeTypeName($type) {
    $map['code_no'] = $type;
    $map['parent_no'] = 'notify';
    return M('sys_code')->where($map)->getField('code_name');
}

//公告发布状态
function getNoticeStatus($status) {
    switch ($status) {
        case 0:
            $str = '<font color="orange"><b>未发布</b></font>';
            break;
        case 1:
            $str = '<font color="green"><b>生效</b></font>';
            break;
        case 2:
            $str = '<font color="blue"><b>待审批</b></font>';
            break;
        case 3:
            $str = '<font color="red"><b>未通过</b></font>';
            break;
    }
    return $str;
}

/**
 * 发起HTTPS请求
 */
function curl_post($url, $data, $header = '', $post = 1) {
    //初始化curl
    $ch = curl_init();
    //参数设置  
    $header || $header[] = "Content-type: text/xml"; //定义content-type为xml
    $res = curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_POST, $post);
    if ($post)
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    $result = curl_exec($ch);

    //连接失败
    if ($result == FALSE) {
        $result = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Response><statusCode>172001</statusCode><statusMsg>网络错误</statusMsg></Response>";
    }
    curl_close($ch);
    return $result;
}

//得到公网IP地址
function the_public_ip() {
    $url = 'http://ip.360.cn/IPShare/info';
    $result = curl_post($url, '', 'Content-type: text/xml', 0);
    $result = json_decode($result, true);
    $ip = $result['ip'];

    return $ip;
}

function getIp() {

    $ip_json = @file_get_contents('http://ip.taobao.com/service/getIpInfo.php?ip=myip');

    $ip_arr = json_decode($ip_json, 1); //JSON格式字符解码

    if ($ip_arr['code'] == 0) {

        return $ip_arr['data']['ip'];
    }
}

//通过中文获取用户Id
function getUserId($str) {
    $userId = M('user')->where('user_name="' . trim($str) . '"')->getField('user_id');
    return $userId ? $userId : 'null';
}

//通过id获取用户中文名
function getUserName($user_id) {
    $userName = M('user')->where('user_id="' . trim($user_id) . '"')->getField('user_name');
    return $userName ? $userName : 'null';
}

/*
 * 返回指定时间段的非工作日天数
 * params   $start_date  开始时间日期格式 0000-00-00
 * params   $end_date  结束时间日期格式 0000-00-00
 * return   int
 */

function getWeekendDays($start_date, $end_date) {
    if (strtotime($start_date) > strtotime($end_date))
        list($start_date, $end_date) = array($end_date, $start_date);

    $start_reduce = $end_add = 0;

    $start_N = date('N', strtotime($start_date));
    $start_reduce = ($start_N == 7) ? 1 : 0;

    $end_N = date('N', strtotime($end_date));
    in_array($end_N, array(6, 7)) && $end_add = ($end_N == 7) ? 2 : 1;

    $days = abs(strtotime($end_date) - strtotime($start_date)) / 86400 + 1;

    return floor(($days + $start_N - 1 - $end_N) / 7) * 2 - $start_reduce + $end_add;
}

/*
 * 获取指定月份工作日
 */

function getMonthWorkDays($year, $month, $day = '') {
    $startDate = strtotime($year . '-' . $month . '-01');
    $day = $day ? $day : date('d');
    $endDate = strtotime($year . '-' . $month . '-' . $day);
    $workDays = [];
    for ($i = $startDate; $i <= $endDate; $i += 86400) {
        $info = getdate($i);
        $date = date('Y-m-d', $i);
        if (!in_array($info['weekday'], ['Saturday', 'Sunday'])) {
            $workDays[] = $date;
        }
    }
    return $workDays;
}

/*
 * 获取本周一和周日
 * return array
 */

function getWeekDate() {
    $date = new \DateTime();
    $date->modify('this week');
    $arr[0] = $date->format('Y-m-d');   //周一
    $date->modify('this week +6 days');
    $arr[1] = $date->format('Y-m-d');   //周日
    return $arr;
}

/**
 *      把秒数转换为时分秒的格式 
 *      @param Int $times 时间，单位 秒 
 *      @param Int $type  0:天时分秒  1:分钟  2:天（按工作日8小时算）
 *      @return String 
 */
function secsToStr($secs, $type = 0) {
    if ($type == 1) {
        if ($secs >= 60) {
            $minutes = floor($secs / 60);
            $secs = $secs % 60;
            $r = $minutes;
        }
    } elseif ($type == 2) {
        $days = round(($secs / 28800), 2);
        $r = $days;
    } else {
        if ($secs >= 86400) {
            $days = floor($secs / 86400);
            $secs = $secs % 86400;
            $r = $days . '天';
        }
        if ($secs >= 3600) {
            $hours = floor($secs / 3600);
            $secs = $secs % 3600;
            $r .= $hours . '时';
        }
        if ($secs >= 60) {
            $minutes = floor($secs / 60);
            $secs = $secs % 60;
            $r .= $minutes . '分';
        }
        $r .= $secs . '秒';
    }
    return $r;
}

/*
 * 获取每个月第一天和最后一天
 * param $data 日期 例：2018-01-01
 * param $type  0返回数组   1返回年-月字符串
 * return 时间戳
 */

function getthismonth($date, $type = 0) {
    $firstday = date('Y-m-01 00:00:00', strtotime($date));
    $lastday = date('Y-m-d 00:00:00', strtotime("$firstday +1 month -1 day"));
    if ($type) {
        return substr($firstday, 0, 7);
    } else {
        return array($firstday, $lastday);
    }
}

/*
 * 下载远程文件并保存至本地
 * param string $attachment_id  pc端上传附件的保存位置
 * param string $attachment_name  pc端上传附件的文件名
 * param string $dirName    目录名
 * param string $uploads    移动端保存的文件名
 * param string $uploads_url    移动端保存的文件路径
 * param int    $download   是否下载至本地  0否  1是
 * return array $download = 0:返回PC端和移动端的附件数组
 *              $download = 1:返回PC端和移动端的附件数组，并且将PC端文件下载到本地
 */

function downloadFile($attachment_id, $attachment_name, $dirName, $uploads = '', $uploads_url = '', $download = 0) {
    $http = new \Org\Net\Http();
    $upload['pcUrls'] = explode(',', rtrim($attachment_id, ','));
    $upload['pcNames'] = explode('*', rtrim($attachment_name, '*'));
    $names = strpos($uploads, ';') !== false ? explode(';', $uploads) : $uploads;
    $urls = strpos($uploads_url, ';') !== false ? explode(';', $uploads_url) : $uploads_url;

    if ($upload['pcUrls'][0]) {
        for ($i = 0; $i < count($upload['pcUrls']); $i++) {
            $start = stripos($upload['pcUrls'][$i], '@') + 1;
            $len = stripos($upload['pcUrls'][$i], '_') - $start;
            $directory = substr($upload['pcUrls'][$i], $start, $len);
            // echo $directory,'<br/>';
            $ext = end(explode('.', $upload['pcNames'][$i]));
            $name = end(explode('_', $upload['pcUrls'][$i]));
            $oldName = 'http://www.jsumt.com:85/attach/' . $dirName . '/' . $directory . '/' . $name . '.' . $upload['pcNames'][$i];
            $newName = date('Ymd') . mt_rand(0000, 9999) . '.' . $ext;

            if (!$download) {
                $data[$i]['name'] = $upload['pcNames'][$i];
                $data[$i]['upload'] = $oldName;
            } else {
                //创建目录
                $dir = './Public/Uploads/upload/' . $directory;
                if (!is_dir($dir)) {
                    mkdir($dir, 0777);
                }
                //下载到本地
                $result = $http::curlDownload($oldName, $dir . '/' . $newName);
            }
        }
        if ($urls[0]) {
            for ($i = 0; $i < count($names); $i++) {
                if ($names[$i]['name']) {
                    $tmp[$i]['name'] = $names[$i];
                    $tmp[$i]['upload'] = $urls[$i];
                }
            }
            $data = array_merge($data, $tmp);
        }
    } else {
        //无PC端附件
        if (is_array($names)) {
            for ($i = 0; $i < count($names); $i++) {
                if ($names[$i]['name']) {
                    $data[$i]['name'] = $names[$i];
                    $data[$i]['upload'] = $urls[$i];
                }
            }
        } else {
            $data[0]['name'] = $names;
            $data[0]['upload'] = $urls;
        }
    }

    return $data;
}

/*
 * 获取不同考勤类型数据
 * $data    array
 * $type    int     1:返回每天上班打卡时间和下班打卡时间   
 *                  2：返回迟到信息
 *                  3: 返回缺打卡信息
 *                  4: 当日打卡信息
 *                  5：返回早退信息
 * return array
 */

function getMinOrMax($datas, $type = 1, $month = '', $year = '', $today = '') {
    $month = $month ? $month : date('m');
    $year = $year ? $year : date('Y');
    $today = $today ? $today : date('d');
    $lists = [];
    foreach ($datas as $key => $row) {
        //取最小值
        $day = explode(' ', trim($row['stime']));
        $row['date'] = $day[0];
        $time = explode(':', $day[1]);
        $row['time'] = substr($day[1], 0, 5);
        $lists[$day[0]][] = $row;
        $len = count($lists[$day[0]]);
        if ($row['time'] < '12:00') {
            $data[$day[0]]['min'] = $lists[$day[0]][0];
        }
        if ($row['time'] > '13:00') {
            $data[$day[0]]['max'] = $lists[$day[0]][$len - 1];
        }
        //$data[$day[0]]['id'] = $row['id'];
    }

    switch ($type) {
        case 1:
            $data = $data;
            break;
        case 2:
            $late = [];
            foreach ($data as $key => $row) {
                if ($row['min']['time'] > '08:35') {
                    $late[$key]['min'] = $row['min'];
                }
            }
            $data = $late;
            break;
        case 3:
            $lose = [];
            $workDays = getMonthWorkDays($year, $month, $today);
            foreach ($data as $key => $row) {
                if (!in_array($key, $workDays)) {
                    $lose[$key]['min'] = $lose[$key]['max'] = $key;
                } else {
                    if (!isset($row['min'])) {
                        $lose[$key]['min'] = $key;
                        $lose[$key] = $row;
                    }
                    if (!isset($row['max'])) {
                        $lose[$key] = $row;
                        $lose[$key]['max'] = $key;
                    }
                }
            }

            $data = $lose;
            break;
        case 4:
            if (count($data) == 1) {
                foreach ($data as $key => $row) {
                    $data = $data[$key];
                }
            }
            break;
        case 5:
            $early = [];
            foreach ($data as $key => $row) {
                if ($row['max']['time'] && $row['max']['time'] < '17:25') {
                    $early[$key]['max'] = $row['max'];
                }
            }
            $data = $early;
            break;
    }

    return $data;
}

/*
 * 及时任务按紧急程度显示颜色
 */

function getColorName($flag) {
    switch ($flag) {
        case 1: //紧急
            $color = '#E43127';
            break;
        case 2: //重要
            $color = '#EA6900';
            break;
        case 3: //一般
            $color = '#235AA3';
            break;
    }
    return $color;
}

function getPlanFlagName($flag) {
    switch ($flag) {
        case 1: //紧急
            $str = '紧急';
            break;
        case 2: //重要
            $str = '重要';
            break;
        case 3: //一般
            $str = '一般';
            break;
    }
    return $str;
}

/*
 * 计划类型未读标记
 */

function getPlanTypeFlag($lists) {
    //取所有人
    $reader = [];
    $flag = 0;
    foreach ($lists as $key => $row) {
//        if ($row['manager']) {
//            $users = explode(',', rtrim($row['manager'], ','));
//            foreach ($users as $k => $v) {
//                array_push($allUsers, $v);
//            }
//        }
//        if ($row['participator']) {
//            $users = explode(',', rtrim($row['participator'], ','));
//            foreach ($users as $k => $v) {
//                array_push($allUsers, $v);
//            }
//        }
//        if ($row['to_id']) {
//            $where['dept_id'] = array('in', explode(',', rtrim($row['to_id'], ',')));
//            $users = M('user')->where($where)->getField('user_id', true);
//            if (!is_array($users)) {
//                $users[] = $users;
//            }
//            foreach ($users as $k => $v) {
//                array_push($allUsers, $v);
//            }
//        }
        if ($row['reader']) {
            $reader = explode(',', $row['reader']);
            if (!in_array(session('user_id'), $reader)) {
                $flag = 1;
            }
        } else {
            $flag = 1;
        }
    }
    return $flag;
}

/**
 * 数据导出为excel格式， 示例
 */
function getExcel($fileName, $headArr, $data) {
    //对数据进行检验
    if (empty($data) || !is_array($data)) {
        die("data must be a array");
    }
    //检查文件名
    if (empty($fileName)) {
        exit;
    }

    $fileName .= ".xls";

    //创建PHPExcel对象，注意，不能少了\
    //导入PHPExcel类库
    import("Org.Util.PHPExcel");

    $objPHPExcel = new PHPExcel();
    $objProps = $objPHPExcel->getProperties();
    foreach ($data as $s => $sheet) {//sheet写入
        $GSheet = $s + 1;
        if ($s == 0) {
            $objPHPExcel->setActiveSheetIndex($s);
            $objActSheet = $objPHPExcel->getActiveSheet();
            $objActSheet->setTitle('sheet' . $GSheet);
        } else {
            //添加一个新的worksheet
            $objPHPExcel->createSheet();
            $objActSheet = $objPHPExcel->getSheet($s);
            $objActSheet->setTitle('sheet' . $GSheet);
        }


        //设置表头
        $key = ord("A");
        foreach ($headArr as $v) {
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex($s)->setCellValue($colum . '1', $v);
            $key += 1;
        }

        $column = 2;
        foreach ($sheet as $key => $rows) { //行写入
            $span = ord("A");
            foreach ($rows as $keyName => $value) {// 列写入
                $j = chr($span);
                $objActSheet->setCellValue($j . $column, $value);
                $span++;
            }
            $column++;
        }
    }

//     $fileName = iconv("utf-8", "gb2312", $fileName);
//    echo $fileName;die;
//重命名表
// $objPHPExcel->getActiveSheet()->setTitle('test');
//设置活动单指数到第一个表,所以Excel打开这是第一个表
    $objPHPExcel->setActiveSheetIndex(0);

    ob_end_clean(); //清除缓冲区,避免乱码
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename=\"$fileName\"");
    header('Cache-Control: max-age=0');
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output'); //文件通过浏览器下载
    exit;
}

/**
 * importExcel
 * 导入excel表格 组成数组
 * 
 * @access public
 * @param string $path 文件路径
 * @return type 
 * @author  fangzheng<zheng.fang@wemax.org> 
 */
function importExcel($path) {
    //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
    import("Org.Util.PHPExcel");
    //要导入的xls文件，位于根目录下的Public文件夹
    $filename = $path;
    //创建PHPExcel对象，注意，不能少了\
    $PHPExcel = new \PHPExcel();
    //如果excel文件后缀名为.xls，导入这个类
//    import("Org.Util.PHPExcel.Reader.Excel5");
    //    $PHPReader = new \PHPExcel_Reader_Excel5();
    //如果excel文件后缀名为.xlsx，导入这下类
    import("Org.Util.PHPExcel.Reader.Excel2007");
    $PHPReader = new \PHPExcel_Reader_Excel2007();

    //载入文件
    $PHPExcel = $PHPReader->load($filename);
    //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
    $sheetCount = $PHPExcel->getSheetCount();

    for ($i = 0; $i < $sheetCount; $i++) {
        //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
        $currentSheet = $PHPExcel->getSheet($i);
        //获取总列数
        $allColumn = $currentSheet->getHighestColumn();
        //获取总行数
        $allRow = $currentSheet->getHighestRow();
        //循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
        for ($currentRow = 1; $currentRow <= $allRow; $currentRow++) {
            //从哪列开始，A表示第一列
            for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) {
                //数据坐标
                $address = $currentColumn . $currentRow;
                //读取到的数据，保存到数组$arr中
//                if ($currentColumn == 'D') { //D列是时间
//                    $arr[$i][$currentRow][$currentColumn] = gmdate("Y/m/d H:i:s", PHPExcel_Shared_Date::ExcelToPHP($currentSheet->getCell($address)->getValue()));
//                } else {
//                    $arr[$i][$currentRow][$currentColumn] = $currentSheet->getCell($address)->getValue();
//                }
                $arr[$i][$currentRow][$currentColumn] = $currentSheet->getCell($address)->getValue();
            }
        }
    }

    return $arr;
}

//无限分类
function getTree($arr, $id, $step = '') {
    static $tree = [];
    foreach ($arr as $key => $val) {
        if ($val['pid'] == $id) {
            $flg = str_repeat('&nbsp;&nbsp;', $step);
            $val['type_name'] = $flg . $val['type_name'];
            $tree[] = $val;
            getTree($arr, $val['type_id'], $step + 1);
        }
    }


    return $tree;
}

//获取计划汇报周期
function getPlanCycle($type) {
    switch ($type) {
        case 1:
            $name = '一周一报';
            break;
        case 2:
            $name = '一周两报';
            break;
        case 3:
            $name = '一月一报';
            break;
    }
    return $name;
}

//标的物类型
function getAttchType($type) {
    switch ($type) {
        case 1:
            $name = 'word';
            break;
        case 2:
            $name = 'Excel';
            break;
        case 3:
            $name = 'PPT';
            break;
        case 4:
            $name = 'code';
            break;
    }
    return $name;
}

//获取子分类名称
function getChildType($type) {
    return M('plan_type')->where('type_id = ' . $type)->getField('type_name');
}

function find_id($string, $id) {
    $string = ltrim($string, ",");
    if ($id == "" || $id == ",")
        return false;
    if (substr($string, -1) != ",")
        $string .= ",";
    if (strpos($string, "," . $id . ",") > 0)
        return true;
    if (strpos($string, $id . ",") === 0)
        return true;
    if (!strstr($id, ",") && $string == $id)
        return true;
    return false;
}

function get_week($string) { //-- 返回形如 六
    switch (date("w", strtotime($string))) {
        case 0:
            return "日";
        case 1:
            return "一";
        case 2:
            return "二";
        case 3:
            return "三";
        case 4:
            return "四";
        case 5:
            return "五";
        case 6:
            return "六";
    }
}

//获取物品名称
function getGoodsName($id) {
    return M('goods')->where('id=' . $id)->getField('name');
}

//获取物品类别
function getGoodsType($goods_id) {
    $type = M('goods')->where('id=' . $goods_id)->getField('type');
    return M('goods_type')->where('id=' . $type)->getField('name');
}

//获取指定时间段有几周
function get_weekinfo($startDate, $endDate) {
    $n = (strtotime($endDate) - strtotime($startDate)) / 86400;
    $endDate = date("Y-m-d 00:00:00", strtotime("$endDate +1 day"));
    if ($n < 7) {
        //查开始时间 在 那周 的 位置
        $day = date("w", strtotime($startDate)) - 1;
        //查开始时间  那周 的 周一
        $week_start = date("Y-m-d 00:00:00", strtotime("$startDate -{$day} day"));
        //查开始时间  那周 的 周末
        $day = 7 - $day;
        $week_end = date("Y-m-d 00:00:00", strtotime("$startDate +{$day} day"));
        //判断周末时间是否大于时间段的结束时间，如果大于，那就是时间段在同一周，否则时间段跨两周
        if ($week_end >= $endDate) {
            $weekList[] = array($startDate, $endDate);
        } else {
            $weekList[] = array($startDate, $week_end);
            $weekList[] = array($week_end, $endDate);
        }
    } else {
        //如果跨度大于等于7天，可能是刚好1周或跨2周或跨N周，先找出开始时间 在 那周 的 位置和那周的周末时间
        $day = date("w", strtotime($startDate)) - 1;
        $week_start = date("Y-m-d 00:00:00", strtotime("$startDate -{$day} day"));
        $day = 7 - $day;
        $week_end = date("Y-m-d 00:00:00", strtotime("$startDate +{$day} day"));
        //先把开始时间那周写入数组
        $weekList[] = array($startDate, $week_end);
        //判断周末是否大于等于结束时间，不管大于(2周)还是等于(1周)，结束时间都是时间段的结束时间。
        if ($week_end >= $endDate) {
            $weekList[] = array($week_end, $endDate);
        } else {
            //N周的情况用while循环一下，然后写入数组
            while ($week_end <= $endDate) {
                $start = $week_end;
                $week_end = date("Y-m-d 00:00:00", strtotime("$week_end +7 day"));
                if ($week_end <= $endDate) {
                    $weekList[] = array($start, $week_end);
                } else {
                    $weekList[] = array($start, $endDate);
                }
            }
        }
    }
    return count($weekList);
}

//获取物品型号
function getGoodsModel($goods_id) {
    return M('goods_put')->where('id=' . $goods_id)->getField('model');
}

//导出excel
function exportExcel($fileName, $headArr, $data) {
    import("Org.Util.PHPExcel");
    //创建对象
    $objPHPExcel = new PHPExcel();
    $objPHPExcel->getProperties()->setCreator("转弯的阳光")
            ->setLastModifiedBy("转弯的阳光")
            ->setTitle("数据EXCEL导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("备份数据")
            ->setKeywords("excel")
            ->setCategory("result file");

    $objActSheet = $objPHPExcel->setActiveSheetIndex(0);

    /* 以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改 */
    //设置表头
    $key = ord("A");
    foreach ($headArr as $v) {
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
        $key += 1;
    }
    $column = 2;


    foreach ($data as $s => $sheet) {//sheet写入
        $span = ord("A");
        foreach ($sheet as $key => $rows) { //行写入
            $j = chr($span);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($j . $column, $rows);
            $span++;
        }
        $column++;
    }
    $objPHPExcel->getActiveSheet()->setTitle('User');
    $objPHPExcel->setActiveSheetIndex(0);
    ob_end_clean();
    header('Content-Type: application/vnd.ms-excel,charset:utf-8');
    header('Content-Disposition: attachment;filename="' . $fileName . '.xls"');
    header('Cache-Control: max-age=0');
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');
    exit;
}

//获取流程分类名
function getFlowSortName($id) {
    $sort_id = M('flow_type')->where('flow_id=' . $id)->getField('flow_sort');
    return M('flow_sort')->where('sort_id=' . $sort_id)->getField('sort_name');
}

//获取流程名称
function getFlowName($id) {
    return M('flow_type')->where('flow_id=' . $id)->getField('flow_name');
}

//获取流程步骤名称
function getFlowProcessName($flow_id, $prcs_id) {
    if ($prcs_id == 'end') {
        return '[结束]';
    } else {
        $map['flow_id'] = $flow_id;
        $map['prcs_id'] = $prcs_id;
        return M('flow_process')->where($map)->getField('prcs_name');
    }
}

//过滤条件字段,过滤为中文
function filterField($condition) {
    $start = stripos($condition, '[');
    $end = stripos($condition, ']');
    if ($start) {
        $str = substr($condition, $start, $end);
        switch ($str) {
            case '[MAIN_USER_SIGN]':
                $fieldName = '[主办人会签意见]';
                break;
            case '[USER_SIGN]':
                $fieldName = '[经办人会签意见]';
                break;
            case '[CUR_FLOW_PRCS]':
                $fieldName = '[当前流程设计步骤号]';
                break;
            case '[MAIN_USER_NAME]':
                $fieldName = '[当前主办人姓名]';
                break;
            case '[MAIN_USER_PRIV]':
                $fieldName = '[当前主办人角色]';
                break;
            case '[MAIN_USER_PRIV_OTHER]':
                $fieldName = '[当前主办人辅助角色]';
                break;
            case '[MAIN_USER_DEPT]':
                $fieldName = '[当前主办人部门]';
                break;
            case '[FLOW_USER_PRIV]':
                $fieldName = '[流程发起人角色]';
                break;
        }
        $end = substr($condition, $end + 1);
        $fieldName = '\'' . $fieldName . $end;
    } else {
        $fieldName = $condition;
    }

    return $fieldName;
}

//过滤条件字段,过滤为英文
function filterFieldEncode($condition) {
    $start = stripos($condition, '[');
    $end = stripos($condition, ']');
    if ($start) {
        $str = substr($condition, $start, $end);
        $end = substr($condition, $end + 1);
        if (preg_match('/[\x{4e00}-\x{9fa5}]/u', $str) > 0) {  //含有中文
            switch ($str) {
                case '[主办人会签意见]':
                    $fieldName = '[MAIN_USER_SIGN]';
                    break;
                case '[经办人会签意见]':
                    $fieldName = '[USER_SIGN]';
                    break;
                case '[当前流程设计步骤号]':
                    $fieldName = '[CUR_FLOW_PRCS]';
                    break;
                case '[当前主办人姓名]':
                    $fieldName = '[MAIN_USER_NAME]';
                    break;
                case '[当前主办人角色]':
                    $fieldName = '[MAIN_USER_PRIV]';
                    break;
                case '[当前主办人辅助角色]':
                    $fieldName = '[MAIN_USER_PRIV_OTHER]';
                    break;
                case '[当前主办人部门]':
                    $fieldName = '[MAIN_USER_DEPT]';
                    break;
                case '[流程发起人角色]':
                    $fieldName = '[FLOW_USER_PRIV]';
                    break;
            }

            $fieldName = '\'' . $fieldName . $end;
        } else {
            $fieldName = $condition;
        }
    } else {
        $fieldName = $condition;
    }

    return $fieldName;
}

//获取新闻类型
function getNewsTypeName($type) {
    $map['code_no'] = $type;
    $map['parent_no'] = 'news';
    return M('sys_code')->where($map)->getField('code_name');
}

//获取流程管理权限类型
function getFlowPrivTypeName($type) {
    switch ($type) {
        case 0:
            $name = '全部';
            break;
        case 1:
            $name = '管理';
            break;
        case 2:
            $name = '监控';
            break;
        case 3:
            $name = '查询';
            break;
        case 4:
            $name = '编辑';
            break;
        case 5:
            $name = '点评';
            break;
    }
    return $name;
}

//获取流程管理权限管理范围
function getFlowPrivScopeName($scope) {
    switch ($scope) {
        case 'ALL_DEPT':
            $name = '全体部门';
            break;
        case 'SELF_ORG':
            $name = '本机构';
            break;
        case 'SELF_DEPT':
            $name = '本部门及下属部门';
            break;
        case 'SELF_BRANCH':
            $name = '本部门（不含下属部门）';
            break;
        case 'CUSTOM':
            $name = '自定义部门';
            break;
    }
    return $name;
}

//获取公文类型
function getDocumentTypeName($type) {
    $map['code_no'] = $type;
    $map['parent_no'] = 'RMS_FILE_KIND';
    return M('sys_code')->where($map)->getField('code_name');
}

/**
 * 根据生日中的年份来计算所属生肖
 * @param int $birth_year
 * @return string
 */
function get_animal($birth_year) {
    //1900年是子鼠年
    $animal = array(
        '鼠', '牛', '虎', '兔', '龙', '蛇',
        '马', '羊', '猴', '鸡', '狗', '猪'
    );

    $my_animal = ($birth_year - 1900) % 12;
    return $animal[$my_animal];
}

/**
 * 根据生日中的月份和日期来计算所属星座
 * @param int $birth_month
 * @param int $birth_date
 * @return string
 */
function get_zodiac_sign($birth_month, $birth_date) {
    //判断的时候，为避免出现1和true的疑惑，或是判断语句始终为真的问题，这里统一处理成字符串形式
    $birth_month = intval($birth_month);
    $constellation_name = array(
        '水瓶座', '双鱼座', '白羊座', '金牛座', '双子座', '巨蟹座',
        '狮子座', '处女座', '天秤座', '天蝎座', '射手座', '摩羯座'
    );
    if ($birth_date <= 22) {
        if (1 !== $birth_month) {
            $constellation = $constellation_name[$birth_month - 2];
        } else {
            $constellation = $constellation_name[11];
        }
    } else {
        $constellation = $constellation_name[$birth_month - 1];
    }
    return $constellation;
}

/*
 * 计算入库、出库数
 * params   $type   1:出库   2入库
 * params   $start  开始日期
 * params   $end    结束日期
 * return   int
 */

function getGoodsCount($type, $gid, $start, $end) {
    $map['goods_id'] = $gid;
    $map['create_time'] = array('between', [$start, $end]);
    if ($type == 1) {
        $outCount = M('goods_out')->where($map)->getField('real_count', true);
        if (!is_array($outCount)) {
            $outCount[] = $outCount;
        }
        $count = array_sum($outCount);
    } else {
        $putCount = M('goods_put')->where($map)->getField('count', true);
        if (!is_array($putCount)) {
            $putCount[] = $putCount;
        }
        $count = array_sum($putCount);
    }
    return $count;
}

//二维数组转一维
function changearray($arr) {
    $newArr = [];
    foreach ($arr as $key => $val) {
        if (is_array($val)) {
            $newArr = array_merge($newArr, $val);
        } else if ($val) {
            array_push($newArr, $val);
        }
    }
    return $newArr;
}

/* 判断流程查询权限
 * 
 */

function hasFlowPriv($flowIds, $ids) {
//    print_r($ids);
    $flag = false;
    if (is_array($ids)) {
        foreach ($flowIds as $key => $row) {
            if (in_array($row, $ids)) {
                $flag = true;
                break;
            }
        }
    } else {
        if (in_array($ids, $flowIds)) {
            $flag = true;
        }
    }
//    var_dump($flag);
    return $flag;
}

/* 获取当前用户流程权限：查询或全部
 * $type 3:查询权限  0管理权限  1:所有权限
 * return flow_ids
 */

function getUserFlowPriv($type) {
    if ($type !== 1) {
        $privMap['priv_type'] = $type;  //权限
        //获取当前用户的id,部门，角色
        $privMap['USER'] = array('like', '%' . session('user_id') . '%');
        $flowIds[0] = M('flow_priv')->where($privMap)->getField('flow_id', true);

        if (session('dept_id_other')) {
            $dept = explode(',', rtrim(session('dept_id_other'), ','));
            array_push($dept, session('dept_id'));
        } else {
            $dept[] = session('dept_id');
        }
        foreach ($dept as $key => $row) {
            unset($privMap['USER']);
            $privMap['DEPT'] = array('like', '%' . $row . '%');
            $ids[] = M('flow_priv')->where($privMap)->getField('flow_id', true);
        }
        $flowIds[1] = changearray($ids);

        if (session('user_priv_other')) {
            $priv = explode(',', rtrim(session('user_priv_other'), ','));
            array_push($priv, session('user_priv'));
        } else {
            $priv[] = session('user_priv');
        }
        unset($ids);
        foreach ($priv as $key => $row) {
            unset($privMap['dept']);
            $privMap['role'] = array('like', '%' . $row . '%');
            $ids[] = M('flow_priv')->where($privMap)->getField('flow_id', true);
        }
//                print_r($ids);
        $flowIds[2] = changearray($ids);
    } else {
        $flowIds[] = getUserFlowPriv(0);
        $flowIds[] = getUserFlowPriv(3);
        $flowIds = changearray($flowIds);
    }
    $flowIds = array_unique(changearray($flowIds));

    return $flowIds;
}

function weather_api($city) {
    $host = "http://jisutqybmf.market.alicloudapi.com";
    $path = "/weather/query";
    $method = "GET";
    $appcode = "1215c3a301254ee79ca773ce9054f2ca"; //阿里云appcode
    $headers = array();
    array_push($headers, "Authorization:APPCODE " . $appcode);
    $querys = "city=$city&citycode=citycode&cityid=cityid&ip=ip&location=location";
    $bodys = "";
    $url = $host . $path . "?" . $querys;

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);
    if (1 == strpos("$" . $host, "https://")) {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    $result = curl_exec($curl);
    var_dump($result);
    $data = json_decode($result, true);
    return $data;
}

//获取企业邮token
function getEmailToken($id, $secret) {
    $url = 'https://api.exmail.qq.com/cgi-bin/gettoken?corpid=' . $id . '&corpsecret=' . $secret;
    $result = curl_post($url, '', '', 0);
    $result = json_decode($result, true);
    if ($result['errcode'] == 0) {
        return $result['access_token'];
    } else {
        return $result;
    }
}

//单点登录企业邮
function loginExmail($userid) {
    //获取单点登录token
    $map['webname'] = array('like', '%登录%');
    $row = M('web')->where($map)->find();
    $corpid = trim($row['wx_corpid']);
    $secret = trim($row['wx_appsecret']);
    $token = getEmailToken($corpid, $secret);

    $url = 'https://api.exmail.qq.com/cgi-bin/service/get_login_url?access_token=' . $token . '&userid=' . $userid;
    $result = curl_post($url, '', '', 0);
    $result = json_decode($result, true);
    if ($result['errcode'] == 0) {
        return ['url' => $result['login_url'], 'status' => 1];
    } else {
        return $result;
    }
}

//新邮件数量
function getNewExmailCount($userid) {
    $map['webname'] = array('like', '%新邮件提醒%');
    $row = M('web')->where($map)->find();
    $corpid = trim($row['wx_corpid']);
    $secret = trim($row['wx_appsecret']);
    $token = getEmailToken($corpid, $secret);

    $url = 'https://api.exmail.qq.com/cgi-bin/mail/newcount?access_token=' . $token . '&userid=' . $userid;
    $result = curl_post($url, '', '', 0);
    $result = json_decode($result, true);
    if ($result['errcode'] == 0) {
        return ['count' => $result['count'], 'status' => 1];
    } else {
        return $result;
    }
}

/*  查询邮件
 *  params $token   调用接口凭证
 *  params $begin   开始日期。格式为2016-10-01
 *  params $end     开始日期。格式为2016-10-07
 *  params $type    邮件类型。0:收信+发信 1:发信 2:收信
 *  params $userid  筛选条件：指定成员帐号
 *  params $subject 筛选条件：包含指定主题内容
 */

function getExmailList($begin, $end, $type, $userid, $subject = '') {
    //获取日志查询token
    $map['webname'] = array('like', '%日志查询%');
    $row = M('web')->where($map)->find();
    $corpid = trim($row['wx_corpid']);
    $secret = trim($row['wx_appsecret']);
    $token = getEmailToken($corpid, $secret);

    $url = 'https://api.exmail.qq.com/cgi-bin/log/mail?access_token=' . $token;
    $begin = $begin ? $begin : date('Y-m-01');
    $end = $end ? $end : date('Y-m-d');
    $data = ['begin_date' => $begin, 'end_date' => $end, 'mailtype' => $type, 'userid' => $userid, 'subject' => $subject];
    $data = json_encode($data);
//    echo $data;
    $result = curl_post($url, $data);
    $result = json_decode($result, true);
    if ($result['errcode'] == 0) {
        return $result['list'];
    } else {
        return $result;
    }
}

/*
 * 更新用户邮件id
 * department_id  获取的部门id。id为1时可获取根部门下的成员
 * fetch_child   1/0：是否递归获取子部门下面的成员
 */

function getUserExmail() {
    //获取日志查询token
    $map['webname'] = array('like', '%通讯录管理%');
    $row = M('web')->where($map)->find();
    $corpid = trim($row['wx_corpid']);
    $secret = trim($row['wx_appsecret']);
    $token = getEmailToken($corpid, $secret);
    
    $url = 'https://api.exmail.qq.com/cgi-bin/user/simplelist?access_token='.$token.'&department_id=1&fetch_child=1';
    $result = curl_post($url, $data);
    $result = json_decode($result, true);
    if ($result['errcode'] == 0) {
        return $result['userlist'];
    } else {
        return $result;
    }
}
